package com.atguigu.cloud.service.impl;

import com.atguigu.cloud.apis.AccountFeignApi;
import com.atguigu.cloud.apis.StorageFeignApi;
import com.atguigu.cloud.entities.Order;
import com.atguigu.cloud.mapper.OrderMapper;
import com.atguigu.cloud.resp.ResultData;
import com.atguigu.cloud.service.OrderService;
import io.seata.core.context.RootContext;
import io.seata.spring.annotation.GlobalTransactional;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

/**
 * @Author: interface
 * @Create: 2025/7/29 - 下午3:04
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Resource
    private OrderMapper orderMapper;

    @Resource //OpenFeign远程调用账户服务
    private AccountFeignApi accountFeignApi;

    @Resource //OpenFeign远程调用库存服务
    private StorageFeignApi storageFeignApi;

    @Override
    @GlobalTransactional(name = "zzyy-create-order",rollbackFor = Exception.class) //AT
    public void create(Order order) {
        //获取全局事务id
        String xid = RootContext.getXID();

        // 1.新建订单
        log.info("开始新建订单,全局事务xid:{}", xid);

        // 2. 订单状态: 0:新建, 1:已完结
        order.setStatus(0);

        // 3. 订单插入数据库
        int result = orderMapper.insert(order);
        if (result <= 0) {
            throw new RuntimeException("订单插入失败");
        }

        Order orderFromDB = orderMapper.selectOne(order);
        log.info("订单插入数据库成功,订单信息:{}", orderFromDB);
        System.out.println();

        // 4. 订单微服务开始调用Storage库存，做扣减count
        log.info("-------> 订单微服务开始调用Storage库存，做扣减count");
        ResultData storageResultData = storageFeignApi.decrease(orderFromDB.getProductId(), orderFromDB.getCount());
        if (!storageResultData.getCode().equalsIgnoreCase("200")) {
            throw new RuntimeException("远程调用库存服务失败");
        }

        log.info("-------> 订单微服务结束调用Storage库存，做扣减完成");
        System.out.println();

        // 5. 订单微服务开始调用Account账号，做扣减money
        log.info("-------> 订单微服务开始调用Account账号，做扣减money");
        ResultData accountResultData = accountFeignApi.decrease(orderFromDB.getUserId(), orderFromDB.getMoney());
        if (!accountResultData.getCode().equalsIgnoreCase("200")) {
            throw new RuntimeException("远程调用账户服务失败");
        }
        log.info("-------> 订单微服务结束调用Account账号，做扣减完成");
        System.out.println();

        //6. 修改订单状态 订单状态status：0：创建中；1：已完结
        log.info("-------> 修改订单状态");
        orderFromDB.setStatus(1);
        Example example = new Example(Order.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("id", orderFromDB.getId());
        criteria.andEqualTo("status", 0);

        int updateResult = orderMapper.updateByExampleSelective(orderFromDB, example);
        if(updateResult <= 0) {
            throw new RuntimeException("订单状态更新失败");
        }

        log.info("-------> 修改订单状态完成"+"\t"+updateResult);
        log.info("-------> orderFromDB info: "+orderFromDB);

        System.out.println();
        log.info("==================>结束新建订单"+"\t"+"xid_order:" +xid);

    }
}
